package com.zdpx.pxframework.database;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zdpx.pxframework.core.factory.YamlPropertySourceFactory;
import com.zdpx.pxframework.database.config.DatabaseProperties;
import com.zdpx.pxframework.database.handler.PxMetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 数据库自动配置类
 *
 * @Description:
 * @Author: Cheng XiaoXiao
 * @Date: 2022/2/21  18:21
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.zdpx.*.*.mapper")
@EnableConfigurationProperties({DatabaseProperties.class})
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:mybatis-plus-default.yml")
public class MyBatisPlusAutoConfiguration {

    /**
     * 自动填充数据
     */
    @Bean
    @ConditionalOnMissingBean(PxMetaObjectHandler.class)
    public PxMetaObjectHandler mateMetaObjectHandler() {
        return new PxMetaObjectHandler();
    }

    /**
     * 分页插件
     * @return
     */
    @Bean
    public MybatisPlusInterceptor paginationInnerInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setMaxLimit(1000L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

    @Bean
    public BlockAttackInnerInterceptor mybatisPlusDeleteInterceptor() {
        return new BlockAttackInnerInterceptor();
    }

    /**
     * mybatis-plus 乐观锁拦截器
     */
    @Bean
    public OptimisticLockerInnerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }
}

